import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
import Home from '@/pages/Home'//首页 
import Login from '@/pages/Login'//登录页
import Register from '@/pages/Register'//注册页
import Search from '@/pages/Search'//搜索页
import Detail from '@/pages/Detail'//商品详情页
import AddCartSuccess from '@/pages/AddCartSuccess'//商品加入购物车成功页面
import ShopCart from '@/pages/ShopCart'//购物车页面
import Trade from '@/pages/Trade'//结算页面
import Pay from '@/pages/Pay'//支付页面
import Center from '@/pages/Center'
import MyOrder from '@/pages/Center/myOrder'
import GroupBuy from '@/pages/Center/groupOrder'
//引入store
import store from "@/store";

 
// 解决：Uncaught (in promise) NavigationDuplicated;   同一路径下重复跳转的报错，即：“/search?”跳转“/search?”
let originalPush = Router.prototype.push; // 先保存一份 VueRouter.prototype.push方法
let originalRepace = Router.prototype.replace;
Router.prototype.push = function push(location) {
    // call(); 篡改上下文    catch(); 捕获异常 **** 
    return originalPush.call(this, location).catch(e => e);
}
Router.prototype.replace = function replace(location) {
    return originalRepace.call(this, location).catch(e => e);
}

//对外暴露VueRouter类的实例
let router = new Router({
  routes: [
    {
      name:'home',
      path: '/home',
      component: Home,
      meta:{
        show:true
      }
    },
    {
      // name:"login",
      path: '/login',
      component: Login,
      meta:{
        show:false
      }
    },
    {
      name:'register',
      path: '/register',
      component: Register,
      meta:{
        show:false
      }
    },
    {
      name:'search',
      //:keyword代表params占位符   问号'?'则是代表params可传可不传
      path: '/search/:keyword?',
      component: Search,
      meta:{
        show:true
      }
    },
    {
      path:'*',
      component: Home,
      meta:{
        show:true
      }
    },
    {
      name:'detail',
      path:'/detail/:skuId?',
      component: Detail,
      meta:{
        show:true
      }
    },
    {
      name:'AddCartSuccess',
      path:'/addcartsuccess',
      component: AddCartSuccess,
      meta:{
        show:true
      }
    },
    {
      path: '/shopcart',
      component: ShopCart,
    },
    {
      path: '/trade',
      component: Trade,
      /* 只能从购物车界面, 才能跳转到交易界面 */
      beforeEnter (to, from, next) {
        if (from.path==='/shopcart') {
          next()
        } else {
          next('/shopcart')
        }
      }
    },
    {
      path: '/pay',
      component: Pay,
  
      // 将query参数映射成props传递给路由组件
      props: route => ({orderId: route.query.orderId}),
  
      /* 只能从交易界面, 才能跳转到支付界面 */
      beforeEnter (to, from, next) {
        if (from.path==='/trade') {
          next()
        } else {
          next('/trade')
        }
      }
    },
    {
      path:"/paySuccess",
      component:()=>import("@/pages/PaySuccess"),
      beforeEnter(to,form,next){
        if(form.path==="/pay"){
          next()
        }else{
          next("/pay")
        }
      }
    },
    {
      path:"/center",
      //component: Center,
      component:()=>import("@/pages/Center/index.vue"),
      children:[
        {
          // path: '/center/myorder',
          path: 'myorder',
          component: MyOrder,
        },
        {
          path: 'grouporder',
          component: GroupBuy,
        },
        {
          path: '',
          redirect: 'myorder'
        }
      ]
    }
    
  ],
  //滚动行为
  scrollBehavior(to, from, savedPosition) {
    //返回的这个y=0，代表的滚动条在最上方
    return { x: 0, y: 0 };
  },
})

//导航守卫
router.beforeEach(async (to, from, next) => {
  //to:获取到要跳转到的路由信息
  //from：获取到从哪个路由跳转过来来的信息
  //next: next() 放行  next(path) 放行  
  //方便测试 统一放行
 //  next();
 //获取仓库中的token-----可以确定用户是登录了
  let token  = store.state.user.token;
  let name = store.state.user.userInfo.name;
  //用户登录了
  if(token){
    //已经登录而且还想去登录------不行
    if(to.path=="/login"||to.path=='/register'){
       next('/');
    }else{
      //已经登陆了,访问的是非登录与注册
      //登录了且拥有用户信息放行
      if(name){
        next();
      }else{
        //登陆了且没有用户信息
        //在路由跳转之前获取用户信息且放行
        try {
         await store.dispatch('getUserInfo');
         next();
        } catch (error) {
          //token失效从新登录
          await store.dispatch('userLogout');
          next('/login')
        }
      }
    }
  }else{
     //未登录：不能去交易相关、不能去支付相关【pay|paysuccess】、不能去个人中心
     //未登录去上面这些路由-----登录
     let toPath = to.path;
     if(toPath.indexOf('/trade')!=-1 || toPath.indexOf('/pay')!=-1||toPath.indexOf('/center')!=-1){
       //把未登录的时候向去而没有去成的信息，存储于地址栏中的查询参数位置【路由】
       next('/login?redirect='+toPath);
     }else{
        //去的不是上面这些路由（home|search|shopCart）---放行
        next();
     }
  }
});


export default router